// 图表数据处理工具

/**
 * 从查询结果数据生成图表配置
 * @param {Array} records - 查询结果记录
 * @param {string} chartType - 图表类型 (bar, line, pie)
 * @param {Object} options - 选项配置
 * @returns {Object} ECharts配置对象
 */
export const generateChartFromData = (records, chartType = 'bar', options = {}) => {
  if (!records || records.length === 0) {
    return null;
  }

  const {
    title = '数据图表',
    xField = null, // X轴字段名，如果为null则自动选择
    yField = null, // Y轴字段名，如果为null则自动选择
    groupBy = null // 分组字段
  } = options;

  // 获取所有字段名
  const fields = Object.keys(records[0]);
  
  // 自动选择数值字段作为Y轴
  const numericFields = fields.filter(field => {
    const sampleValue = records[0][field];
    return typeof sampleValue === 'number' || !isNaN(Number(sampleValue));
  });

  // 自动选择文本字段作为X轴
  const textFields = fields.filter(field => {
    const sampleValue = records[0][field];
    return typeof sampleValue === 'string' && !numericFields.includes(field);
  });

  // 确定X轴和Y轴字段
  const finalXField = xField || textFields[0] || fields[0];
  const finalYField = yField || numericFields[0];

  if (!finalXField || !finalYField) {
    console.warn('无法确定X轴或Y轴字段');
    return null;
  }

  // 提取数据
  const xData = records.map(record => record[finalXField]);
  const yData = records.map(record => Number(record[finalYField]));

  // 构建基础配置
  const baseConfig = {
    title: {
      text: title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    }
  };

  // 根据图表类型生成配置
  switch (chartType) {
    case 'bar':
      return {
        ...baseConfig,
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            rotate: xData.length > 5 ? 45 : 0
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: finalYField,
          type: 'bar',
          data: yData,
          itemStyle: {
            color: '#4285f4'
          }
        }]
      };

    case 'line':
      return {
        ...baseConfig,
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: finalYField,
          type: 'line',
          data: yData,
          smooth: true,
          itemStyle: {
            color: '#4285f4'
          }
        }]
      };

    case 'pie':
      const pieData = xData.map((name, index) => ({
        name,
        value: yData[index]
      }));
      
      return {
        ...baseConfig,
        series: [{
          name: finalYField,
          type: 'pie',
          radius: '50%',
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };

    default:
      return null;
  }
};

/**
 * 检测数据是否适合生成图表
 * @param {Array} records - 查询结果记录
 * @returns {Object} 检测结果
 */
export const detectChartSuitability = (records) => {
  if (!records || records.length === 0) {
    return { suitable: false, reason: '无数据' };
  }

  const fields = Object.keys(records[0]);
  const numericFields = fields.filter(field => {
    const sampleValue = records[0][field];
    return typeof sampleValue === 'number' || !isNaN(Number(sampleValue));
  });

  const textFields = fields.filter(field => {
    const sampleValue = records[0][field];
    return typeof sampleValue === 'string' && !numericFields.includes(field);
  });

  if (numericFields.length === 0) {
    return { suitable: false, reason: '无数值字段' };
  }

  if (textFields.length === 0 && records.length > 1) {
    return { suitable: false, reason: '无分类字段' };
  }

  return { 
    suitable: true, 
    numericFields, 
    textFields,
    recommendedType: records.length > 10 ? 'line' : 'bar'
  };
};

/**
 * 从API返回的图表数据中提取ECharts配置
 * @param {Object|String} chartData - API返回的图表数据
 * @returns {Object} ECharts配置对象
 */
export const parseApiChartData = (chartData) => {
  if (!chartData) return null;

  // 如果是字符串，尝试解析JSON代码块
  if (typeof chartData === 'string') {
    try {
      // 移除 ```json 和 ``` 包装
      const jsonMatch = chartData.match(/```json\s*(\{[\s\S]*?\})\s*```/);
      if (jsonMatch) {
        return JSON.parse(jsonMatch[1]);
      } else {
        // 尝试直接解析JSON
        return JSON.parse(chartData);
      }
    } catch (error) {
      console.error('解析图表JSON数据失败:', error);
      return null;
    }
  }

  // 如果已经是完整的ECharts配置
  if (chartData.series && (chartData.xAxis || chartData.legend)) {
    return chartData;
  }

  // 如果是简化的配置格式
  if (chartData.title && chartData.data) {
    return {
      title: chartData.title,
      xAxis: {
        type: 'category',
        data: chartData.data.x || []
      },
      yAxis: {
        type: 'value'
      },
      series: chartData.data.series || []
    };
  }

  return null;
};
